package com.zhong.blog.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhong.blog.config.auth.*;
//import com.zhong.blog.filter.LoginFilter;
import com.zhong.blog.handle.MyAuthenticationFailureHandler;
import com.zhong.blog.handle.MyAuthenticationSuccessHandler;
//import com.zhong.blog.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
    @Autowired
    MyAuthenticationFailureHandler myAuthenticationFailureHandler;
    @Autowired
    MyAuthenticationEntryPoint myAuthenticationEntryPoint;
    @Autowired
    private MyOncePerRequestFilter myOncePerRequestFilter;
    @Autowired
    MyAccessDeniedHandler myAccessDeniedHandler;
    @Autowired
    MyLogoutHandler myLogoutHandler;
    @Autowired
    MyLogoutSuccessHandler myLogoutSuccessHandler;
    //  向spring容器中创建一个Bean
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.cors().and()
//                .formLogin()
//                .usernameParameter("root")
//                .passwordParameter("root")
////                .loginPage("http://localhost:8080/#/logintest")
//                .loginProcessingUrl("/furyLogin") // 登录请求路径
//                .successHandler(myAuthenticationSuccessHandler) // 验证成功处理器
//                .failureHandler(myAuthenticationFailureHandler) // 验证失败处理器
//                .and().authorizeRequests()
//                .antMatchers("/furyLogin").permitAll() // 登录请求路径不进行过滤
//                .antMatchers(HttpMethod.OPTIONS).permitAll()
//                .anyRequest()
//                .authenticated()
////                .and()
////                // 过滤OPTIONS请求
////                .addFilterBefore(new AccessFilter(), WebAsyncManagerIntegrationFilter.class)
////                .cors()
//                .and().csrf().disable(); // 取消跨站请求伪造防护






        http.authorizeRequests()
                .antMatchers(HttpMethod.POST,"/login","/logout","/register").permitAll();

        http.authorizeRequests()
                .antMatchers("/blog/**","/oss/**","/essay/**","/guest/**").permitAll();

        http.authorizeRequests().antMatchers("/**").hasAuthority("admin");


        // 开启授权认证
        http.authorizeRequests()
//                .antMatchers("/blog/*").permitAll()
                .anyRequest().authenticated();
        // 登录配置
        http.logout().logoutUrl("/logout");
        http.formLogin().loginPage("http://localhost:8080/login")
                .loginProcessingUrl("/login");

//        http.formLogin().successHandler(myAuthenticationSuccessHandler);
//        http.formLogin().failureHandler(myAuthenticationFailureHandler);
        http.cors().and().csrf().disable();

//        http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
//                .and().headers().cacheControl();

        //第4步：拦截账号、密码。覆盖 UsernamePasswordAuthenticationFilter过滤器
        http.addFilterAt(myUsernamePasswordAuthenticationFilter() , UsernamePasswordAuthenticationFilter.class);

        //第5步：拦截token，并检测。在 UsernamePasswordAuthenticationFilter 之前添加 JwtAuthenticationTokenFilter
        http.addFilterBefore(myOncePerRequestFilter, UsernamePasswordAuthenticationFilter.class);

        //第6步：处理异常情况：认证失败和权限不足
        http.exceptionHandling().authenticationEntryPoint(myAuthenticationEntryPoint).accessDeniedHandler(myAccessDeniedHandler);

        //第8步：退出
        http.logout().addLogoutHandler(myLogoutHandler).logoutSuccessHandler(myLogoutSuccessHandler);

    }

    @Bean
    MyUsernamePasswordAuthenticationFilter myUsernamePasswordAuthenticationFilter() throws Exception {
        MyUsernamePasswordAuthenticationFilter filter = new MyUsernamePasswordAuthenticationFilter();
        //成功后处理
        filter.setAuthenticationSuccessHandler(myAuthenticationSuccessHandler);
        //失败后处理
        filter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);

        filter.setAuthenticationManager(authenticationManagerBean());
        return filter;
    }
}
